﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows;
using System.Windows.Media;

namespace Robert.TwitBy.Converters
{
    //Using Halfwits StatusSourceConverter
    class StatusSourceConverter : IValueConverter
    {
        private static Regex _linkRegex = new Regex("<a href=\\\"([^\\\"]+)\\\" rel=\\\"nofollow\\\">([^\\<]+)", RegexOptions.Compiled);

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var s = value as string;
            if (s == null) return string.Empty;

            s = System.Web.HttpUtility.UrlDecode(s);

            var match = _linkRegex.Match(s);
            if (match.Groups.Count < 3) return null;

            var uri = match.Groups[1].Value;
            var name = match.Groups[2].Value;

            var textBlock = new TextBlock();

            textBlock.Inlines.Add(" from ");

            var link = new Hyperlink();
            link.TextDecorations = null;
            link.Foreground = new SolidColorBrush(Colors.Coral);
            link.Inlines.Add(name);
            link.ToolTip = "See what " + name + "'s about.";
            link.SetBinding(Hyperlink.CommandProperty,
                new Binding { ElementName = "me", Path = new PropertyPath("DataContext.HyperlinkCommand") });
            link.CommandParameter = uri;

            textBlock.Inlines.Add(link);

            return textBlock;

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
